package remote

import (
	"errors"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/ChanSyncObj"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Json"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Map"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Number"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/String"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Uuid"
	"gitee.com/fierce_wolf/go-fox-edge-common/edgeEnv"
	"gitee.com/fierce_wolf/go-fox-edge-iot-common/iotRemote"
	"go-fox-edge-iot-thingspanel/component"
	"net/http"
	"strings"
)

type remoteCloud struct {
}

func (e *remoteCloud) executePost(topic string, body map[string]interface{}, timeout int64) map[string]interface{} {
	// 补齐uuid
	uuid := Map.GetString(body, "uuid", "")
	if uuid == "" {
		uuid = Uuid.RandomUUID()
		body["uuid"] = uuid
	}

	// 发出数据
	jsn := Json.BuildJson(body)
	iotRemote.Mqtt.Publish(topic, jsn, 10*1000)

	// 等待数据返回
	data := ChanSyncObj.SimpleWait(uuid, timeout)
	if data == nil {
		return nil
	}

	return data.(map[string]interface{})
}

func (e *remoteCloud) PublishEntity(entityType string, dataList map[string]interface{}) {
	topic := component.LocalConfig.Publish + "/" + strings.ToLower(entityType) + "/rows"

	body := make(map[string]interface{})
	body["edgeId"] = edgeEnv.GetCPUID()
	body["entityType"] = entityType
	body["data"] = make(map[string]interface{})

	if dataList != nil {
		body["data"] = dataList
	}

	// 发出数据
	jsn := Json.BuildJson(body)
	iotRemote.Mqtt.Publish(topic, jsn, 10*1000)
}

func (e *remoteCloud) QueryTimestamp(entityType string, timeout int64) (int64, error) {
	topic := component.LocalConfig.Publish + "/" + strings.ToLower(entityType) + "/timestamp"

	data := make(map[string]interface{})
	data["edgeId"] = edgeEnv.GetCPUID()
	data["entityType"] = String.CamelName(entityType)

	body := make(map[string]interface{})
	body["data"] = data

	respond := e.executePost(topic, body, timeout)
	if respond == nil {
		return 0, errors.New("未接收到服务端的返回")
	}

	// 检查：是否返回了异常
	code := Map.GetInt(respond, "code", 0)
	msg := Map.GetString(respond, "msg", "")
	if http.StatusOK != code {
		return 0, errors.New("未返回成功代码，这是一个异常的返回:" + msg)
	}

	// 检查：是否有返回了数据
	data = Map.GetMap(respond, "data", nil)
	if data == nil {
		return 0, errors.New("返回的data为空")
	}

	id, ok := data["lastId"]
	if !ok {
		return 0, errors.New("返回的lastId为空")
	}

	return Number.MakeInt64(id), nil
}
